from app.utils.ros_utils import ROSUtils

class RosService:
    def __init__(self, ros_utils, launch_files):
        self.ros_utils = ros_utils
        self.launch_files = launch_files
    
    def control_nodes(self, status):
        """控制ROS节点"""
        if status == 1:  # 启动
            if self.ros_utils.are_ros_processes_running():
                return {
                    "code": 400,
                    "message": "ROS节点已在运行中",
                    "data": None
                }
            
            success_count, failed_launches = self.ros_utils.start_ros_nodes(self.launch_files)
            running_count, _ = self.ros_utils.get_ros_status()
            
            if running_count == len(self.launch_files):
                return {
                    "code": 200,
                    "message": f"所有ROS节点启动成功 ({success_count}/{len(self.launch_files)})",
                    "data": {"success_count": success_count, "total": len(self.launch_files)}
                }
            else:
                return {
                    "code": 206,
                    "message": f"部分ROS节点启动成功 ({running_count}/{len(self.launch_files)})",
                    "data": {
                        "success_count": running_count,
                        "total": len(self.launch_files),
                        "failed": failed_launches
                    }
                }
        
        elif status == 2:  # 重启
            self.ros_utils.stop_ros_nodes()
            
            success_count, failed_launches = self.ros_utils.start_ros_nodes(self.launch_files)
            running_count, _ = self.ros_utils.get_ros_status()
            
            if running_count == len(self.launch_files):
                return {
                    "code": 200,
                    "message": f"所有ROS节点重启成功 ({success_count}/{len(self.launch_files)})",
                    "data": {"success_count": success_count, "total": len(self.launch_files)}
                }
            else:
                return {
                    "code": 206,
                    "message": f"部分ROS节点重启成功 ({running_count}/{len(self.launch_files)})",
                    "data": {
                        "success_count": running_count,
                        "total": len(self.launch_files),
                        "failed": failed_launches
                    }
                }
        
        elif status == 3:  # 停止
            self.ros_utils.stop_ros_nodes()
            return {
                "code": 200,
                "message": "所有ROS节点已停止",
                "data": None
            }
        
        else:
            return {
                "code": 400,
                "message": "无效的status参数",
                "data": None
            }